/* eslint-disable multiline-ternary */
import React, { useEffect, useRef, useState } from 'react'
import { Input, NavBar, TextArea } from 'antd-mobile'

import styles from './index.module.scss'
import { RootState } from '@/types/store'
import { useSelector } from 'react-redux'
import { InputRef } from 'antd-mobile/es/components/input'
import { TextAreaRef } from 'antd-mobile/es/components/text-area'
type Props = {
  type: '' | 'name' | 'intro'
  hideinput: () => void
  onUpdate: (key: string, value: string) => void
}

const EditInput = (props: Props) => {
  // 数据回填
  const profile = useSelector((state: RootState) => state.profile.userProfile)
  const [value, setValue] = useState(
    props.type === 'name' ? profile.name : profile.intro
  )
  // 获取光标焦点
  const inputRef = useRef<InputRef>(null)
  const textRef = useRef<TextAreaRef>(null)
  useEffect(
    () => {
      if (props.type === 'name') {
        inputRef.current!.focus()
      } else {
        textRef.current!.focus()
        // 让textarea光标定位在最后一个字符
        document.querySelector('textarea')!.setSelectionRange(-1, -1)
      }
    },
    [props.type]
  )
  return (
    <div className={styles.root}>
      <NavBar
        onBack={() => {
          props.hideinput()
        }}
        className="navbar"
        right={
          <span
            className="commit-btn"
            onClick={() => props.onUpdate(props.type, value)}>
            提交
          </span>
        }>
        编辑{props.type === 'name' ? '昵称' : '简介'}
      </NavBar>

      <div className="edit-input-content">
        <h3>{props.type === 'name' ? '昵称' : '简介'}</h3>

        {props.type === 'name' ? (
          <div className="input-wrap">
            <Input
              placeholder="请输入昵称"
              value={value}
              ref={inputRef}
              onChange={(e) => {
                setValue(e)
              }}
            />
          </div>
        ) : (
          <TextArea
            className="textarea"
            placeholder="请输入简介"
            value={value}
            ref={textRef}
            onChange={(e) => setValue(e)}
            showCount
            maxLength={99}
          />
        )}
      </div>
    </div>
  )
}

export default EditInput
